package com.gjy.concurrency.juc;

import org.jetbrains.annotations.NotNull;

import java.time.LocalDateTime;
import java.util.concurrent.*;

/**
 * @author 宫静雨
 * @version 1.0
 * @since 2023-02-20 16:23:09
 */
public class ScheduleTest {

    private static final ScheduledExecutorService pool = Executors.newScheduledThreadPool(3);

    public static void main(String[] args) {
        DelayQueue<DelayedRun> queue = new DelayQueue<>();
    }

    private static final class DelayedRun implements Delayed {

        @Override
        public long getDelay(@NotNull TimeUnit unit) {
            return 0;
        }

        @Override
        public int compareTo(@NotNull Delayed o) {
            return 0;
        }
    }

    /**
     * 按照时间间隔+运行时间 运行
     */
    private static void withFixedDelay() {
        pool.scheduleWithFixedDelay(() -> {
            System.out.println("Hello: " + LocalDateTime.now());
            try {
                TimeUnit.SECONDS.sleep(4);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }, 3, 3, TimeUnit.SECONDS);
        System.out.println("Hello: " + LocalDateTime.now());
    }

    /**
     * 按照固定时间间隔运行，运行时间超过间隔时间时，
     */
    private static void atFixedRate() {
        pool.scheduleAtFixedRate(() -> {
            System.out.println("Hello: " + LocalDateTime.now());
            try {
                TimeUnit.SECONDS.sleep(4);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }, 3, 3, TimeUnit.SECONDS);
        System.out.println("Hello: " + LocalDateTime.now());
    }
}
